package com.tang.sys.service.impl;

import com.tang.enums.AppHttpCodeEnum;
import com.tang.sys.ResponseResult;
import com.tang.sys.entity.LoginUser;
import com.tang.sys.entity.User;
import com.tang.sys.mapper.UserMapper;
import com.tang.sys.service.ILoginService;
import com.tang.sys.vo.BlogUserLoginVo;
import com.tang.sys.vo.UserInfoVo;
import com.tang.utils.BeanCopyUtils;
import com.tang.utils.JwtUtil;
import com.tang.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否认证通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //查询该用户的状态信息
        String status = loginUser.getUser().getStatus();
        // 判断用户状态是否被禁用
        if ("1".equals(status)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_FORBIDDEN);
        }


        //把用户信息存入redis
        // 将登录用户信息和状态信息存入 Redis
        String redisKey = "login:" + userId;
        redisCache.setCacheObject(redisKey, loginUser);
        redisCache.setCacheObject(redisKey + ":status", status);

        //把token封装 返回
        Map<String,String> map = new HashMap<>();


        map.put("token",jwt);
        map.put("status",status);
        return ResponseResult.okResult(map);
    }

    //注销
    @Override
    public ResponseResult logout() {
        //获取token解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getUser().getId();

        //删除redis中的用户信息
        redisCache.deleteObject("login:"+userId);

        return ResponseResult.okResult();
    }
}